<script setup>
import {getCurrentInstance, reactive, ref} from "vue";
import {cloneDeep} from "lodash";
import {addFileCate, getFileCate, updateFileCate} from "@/api/system/file_cate";

const {proxy} = getCurrentInstance();
const emit = defineEmits(['success']);
const modalRef = ref();
const formRef = ref();
const formData = ref({
  id: undefined,
  type: '',
  name: '',
})
const rules = reactive({
  name: [{required: true, message: '请输入分类名称', trigger: 'blur'}],
})
const formType = ref('create')


const open = async (cateId, type = 'create', fileType) => {
  formType.value = type;
  resetForm();
  if (type === 'create') {
    formData.value.type = fileType;
  } else {
    const {data} = await getFileCate(cateId);
    formData.value = {
      ...data
    }
  }
  modalRef.value.handleOpen()
}

const handleSubmit = async () => {
  await formRef.value.validate();
  let data = cloneDeep(formData.value);
  if (data.id === undefined) {
    await addFileCate(data);
    proxy.$modal.okNotify('新增成功');
  } else {
    await updateFileCate(data);
    proxy.$modal.okNotify('修改成功');
  }
  resetForm();
  modalRef.value.handleClose();
  emit('success')
}

const resetForm = () => {
  formRef.value?.resetFields();
  formData.value = {
    id: undefined,
    type: '',
    name: ''
  }
}

defineExpose({open})
</script>

<template>
  <dialog-form ref="modalRef" :modalTitle="`${formType === 'create' ? '新建' : '编辑'}文件分组`" modalWidth="500px"
               @submit="handleSubmit">
    <a-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <a-form-item label="分组名称" name="name">
        <a-input v-model:value="formData.name" placeholder="请输入分组名称"/>
      </a-form-item>
    </a-form>
  </dialog-form>
</template>

<style scoped lang="scss">

</style>
